<!--
 * @Description:
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-18 15:14:37
-->
<template>
  <div>
    <p>provideB.vue 孙子级组件</p>
    <button @click="changeColor1">子组件修改provide值为yellow</button>
    <button @click="changeColor2">子组件不可修改provide值为yellow</button>
    <div class="box1"></div>
    <div class="box2"></div>
    <hr />
  </div>
</template>
<script setup lang="ts">
import { ref, inject } from 'vue'
import type { Ref } from 'vue'
const color1 = inject<Ref<string>>('color1')
const color2 = inject<Ref<string>>('color2')
const changeColor1 = () => {
  // color1 是联合类型
  // color1?.value = 'yellow' 所以这种方式会报错
  // 有两种方式解决
  // 一是可以使用这种非空断言 color1!.value = 'yellow'
  // 二是在inject时设定默认值 color1 = inject<Ref<string>>('color1', ref('red'))
  color1!.value = 'yellow'
}

const changeColor2 = () => {
  color2!.value = 'yellow'
}
</script>
<style scoped>
h1,
h2,
h3,
hr {
  margin: 10px 0;
}
.box1 {
  width: 50px;
  height: 50px;
  border: 1px solid #ccc;
  background-color: v-bind(color1);
}
.box2 {
  width: 50px;
  height: 50px;
  border: 1px solid #ccc;
  background-color: v-bind(color2);
}
</style>
